<template>
  <div class="app-container" style="height: calc(100vh - 100px)">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="客户姓名">
          <el-input v-model="queryParams.applyName" placeholder="请输入客户姓名" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="设备序列号">
          <el-input v-model="queryParams.imei" placeholder="请输入设备序列号" clearable @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="add">新增</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="postList" stripe border max-height="500">
        <el-table-column label="客户姓名" align="center" prop="applyName"/>
        <el-table-column label="性别" align="center">
          <template #default="scope">
            <span>
              {{
                sys_user_sex.find((item) => item.value == scope.row.sex)
                    ? sys_user_sex.find((item) => item.value == scope.row.sex)
                        .label
                    : ""
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="age"/>
        <el-table-column label="电话" align="center" prop="telephone"/>
        <el-table-column label="家庭住址" align="center" prop="address" width="500"></el-table-column>
        <el-table-column label="产品名称" align="center" prop="modelName"/>
        <el-table-column label="设备编号" align="center" prop="imei"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="edit(scope.row)">解除绑定</el-button>
            <el-button link type="primary" v-if="isAgentPeople" @click="handinfo(scope.row)">视频通话</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.limit" @pagination="getList"/>
    </el-card>

    <!-- 新增设备弹框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="600px" v-if="open" @close="cancel" :close-on-click-modal="false">
      <el-form ref="deviceDindingRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="客户名称" prop="homeBedApplyId">
          <el-select v-model="form.homeBedApplyId" clearable @change="changeHomeBedApplyId" placeholder="请选择产品名称" style="width: 100%">
            <el-option v-for="dict in applyPeople" :key="dict.homeBedApplyId" :label="dict.applyName" :value="dict.homeBedApplyId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="modelId">
          <el-select v-model="form.modelId" clearable @change="changeModelId" placeholder="请选择产品名称" style="width: 100%">
            <el-option v-for="dict in modelData" :key="dict.modelId" :label="dict.modelName" :value="dict.modelId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编号" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入设备编号"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div>
      <dialogComponent
          ref="dialogRef"
          v-show="screen"
          :homeBedApplyId="homeBedApplyId"
          :homeBedApplyName="homeBedApplyName"
          :imei="imei"
          @closed="closed"
          @hideDialog="hideDialog"
      ></dialogComponent>
    </div>
  </div>
</template>

<script setup name="deviceBind">
  const {proxy} = getCurrentInstance();

  import dialogComponent from './dialog.vue';

  const {sys_normal_disable, sys_user_sex} = proxy.useDict(
      "sys_normal_disable",
      "sys_user_sex",
  );
  const router = useRouter();

  import {debounce} from "@/utils/debounce.js";

  import {
    smartSpeakerList,
    getApplySelectOptions,
    getModelSelectOptions,
    deviceBind,
    deviceUnbind, isAgent
  } from "@/api/smartSpeaker/index"

  const showSearch = ref(true);
  const loading = ref(true);
  const postList = ref([]);
  const open = ref(false);
  const title = ref("新增设备");
  const screen = ref(false);
  const homeBedApplyId = ref('');
  const homeBedApplyName = ref('');
  const imei = ref('');
  const isAgentPeople = ref(false);

  const total = ref(0);
  const applyPeople = ref([]);
  const modelData = ref([]);
  const name = ref("");

  const data = reactive({
    form: {},
    queryParams: {
      page: 1,
      limit: 10,
      applyName: undefined,
      imei: undefined,
    },
    rules: {
      homeBedApplyId: [
        { required: true, message: "请选择客户名称", trigger: "change" },
        { required: true, min: 1, max: 10, message: "客户名称在1-10个字符", trigger: "change" }
      ],
      modelId: [
        { required: true, message: "请选择产品名称", trigger: "change" }
      ],
      imei: [
        { required: true, message: "请输入设备序列号", trigger: "blur" },
        { required: true, min: 1, max: 50, message: "设备序列号1-50个字符" }
      ],
    },
  });

  const {queryParams, form, rules} = toRefs(data);

  /**
   * 提交
   */
  const submitFormDebounceHandler = debounce(submitForm, 500);

  function submitForm() {
    proxy.$refs["deviceDindingRef"].validate((valid) => {
      if (valid) {
        deviceBind(form.value).then((res) => {
          proxy.$modal.msgSuccess("绑定成功");
          cancel();
          getList();
        })
      }
    });
  }

  function add() {
    open.value = true;
  }

  function cancel() {
    open.value = false;
    reset();
  }

  function closed(data) {
    screen.value = data;
  }

  function changeHomeBedApplyId(val) {
    form.value.applyName = applyPeople.value.find(
        (item) => item.homeBedApplyId == val,
    )?.applyName;
  }

  function changeModelId(val) {
    form.value.modelName = modelData.value.find(
        (item) => item.modelId == val,
    )?.modelName;
  }

  function reset() {
    form.value = {
      id: undefined,
      homeBedApplyId: undefined,
      applyName: undefined,
      modelId: undefined,
      modelName: undefined,
      imei: undefined,
    };
    proxy.resetForm("deviceDindingRef");
  }

  function edit(data) {
    proxy.$modal.confirm("是否确认解除绑定该设备？").then(function () {
      return deviceUnbind({id: data.id});
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("解除成功");
    }).catch(() => {});
  }

  /** 查询岗位列表 */
  function getList() {
    loading.value = true;
    smartSpeakerList(queryParams.value).then((response) => {
      postList.value = response.page.list;
      total.value = response.page.totalCount;
      loading.value = false;
    })
  }

  function handleQuery() {
    getList();
  }

  function resetQuery() {
    queryParams.value = {
      page: 1,
      limit: 10,
      applyName: undefined,
      imei: undefined,
    };
    getList();
  }

  const dialogRef = ref();
  const addKey = ref(0);

  function handinfo(data) {
    console.log("【 data 】 = ", data.homeBedApplyId);

    homeBedApplyId.value = data.homeBedApplyId;
    homeBedApplyName.value = data.applyName;
    imei.value = data.imei
    screen.value = true;

    addKey.value++;
    nextTick(() => {
      dialogRef.value.init(data);
    });
  }

  function ApplySelectOptions() {
    getApplySelectOptions().then((res) => {
      applyPeople.value = res.applySelectOptions;
    })
  }

  function ModelSelectOptions() {
    getModelSelectOptions().then((res) => {
      modelData.value = res.modelSelectOptions;
    })
  }

  function isAgentBoole() {
    isAgent().then(res => {
      isAgentPeople.value = res.isAgent
    })

  }

  function hideDialog() {
    screen.value = false
  }

  isAgentBoole()
  getList();
  ModelSelectOptions();
  ApplySelectOptions();

  // function getDevice() {
  //   navigator.getUserMedia =
  //     navigator.getUserMedia ||
  //     navigator.webkitGetUserMedia ||
  //     navigator.mozGetUserMedia ||
  //     navigator.msGetUserMedia;
  //   console.log(
  //     '2222222222222222222222222233',
  //     navigator,
  //     navigator.getUserMedia,
  //   )
  //   if (navigator.getUserMedia) {
  //     navigator.getUserMedia(
  //       { video: true },
  //       function onSuccess(stream) {
  //         alert('摄像头开启成功');
  //       },
  //       function onError(error) {
  //         alert("摄像头错误：", error);
  //       },
  //     );
  //     navigator.getUserMedia(
  //       { audio: true },
  //       function onSuccess(stream) {
  //         alert('麦克风开启成功');
  //       },
  //       function onError(error) {
  //         // alert("麦克风错误：", error);
  //       },
  //     );
  //   } else {
  //     // alert('暂不支持');
  //   }
  // }
  // // 定时获取摄像头麦克风权限，根据业务实际情况调用
  // // 用于定位音视频是否因为权限问题不显示
  //
  // getDevice();
</script>
<style scoped lang="scss">
  .fullicon:hover {
    color: #409eff;
  }

  :deep(.el-dialog.is-fullscreen) {
    width: 90%;
    margin-right: 8px;
  }
</style>
